package com.example.autopia.view.Adapters

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.autopia.databinding.ViewholderParkingItemBinding
import com.example.autopia.model.Item.Parking
import com.example.autopia.view.Listeners.ParkingItemListener

class ParkingItemAdapter () :
    RecyclerView.Adapter<ParkingItemAdapter.ViewHolder>() {

    private lateinit var list : MutableList<Parking>
    private lateinit var listener: ParkingItemListener
     fun attachListener(listener: ParkingItemListener) {
        this.listener = listener
    }

    fun setData(newList : List<Parking>){
        list = newList.toMutableList()
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val inflater = LayoutInflater.from(parent.context)
        val binding = ViewholderParkingItemBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return ViewHolder(binding,inflater)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val news = list[position]
        holder.bind(news,listener)
    }

    override fun getItemCount(): Int {
        return list.size
    }

    inner class ViewHolder(private val binding: ViewholderParkingItemBinding,private val inflater: LayoutInflater) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(parking: Parking, listener: ParkingItemListener) {
            binding.apply {
                tvName.text = parking.name
                tvDescription.text = parking.description
                tvPrice.text = parking.price.toString() + " руб/час"
                tvLastPlaces.text = parking.freePlaces.toString() + " oставшихся мест"

                root.setOnClickListener {
                    listener.onItemClicked(parking)
                }

                btInfo.setOnClickListener {
                    listener.onInfoClicked(parking)
                }
            }
        }
    }
}